//
//  MainViewController.m
//  MainUI
//
//  Created by xalo on 16/4/28.
//  Copyright © 2016年 赵言. All rights reserved.
//

#import "MainViewController.h"
#import "MainModel.h"
#import "XLPhotoCell.h"
#import "WZXLOLCardLayout.h"
#import "DetailViewController.h"
#import "PublishViewController.h"

@interface MainViewController () <UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, PublishViewControllerDelegate>

@property (strong, nonatomic)WZXLOLCardLayout *layout;
@property (strong, nonatomic)NSMutableArray *dataSource;  //数据
@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSLog(@"%@",[SandBoxPaths documentsPath]);
    [self.collectionView registerNib:[UINib nibWithNibName:@"XLPhotoCell" bundle:nil] forCellWithReuseIdentifier:@"CELL"];
    self.collectionView.collectionViewLayout = self.layout;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.dataSource = nil;
    //获取用户的粉丝和关注
    [[AVUser currentUser] getFollowersAndFollowees:^(NSDictionary *dict, NSError *error) {
        
        NSMutableArray *followers = [NSMutableArray array];
        if ([dict[@"followers"] count]) {
            
            [followers addObject:dict[@"followers"]];
        }
        else if ([dict[@"followees"] count]) {
            
            [followers addObject:dict[@"followees"]];
        }
        NSMutableArray *array = followers.firstObject;
        AVQuery *query = [AVQuery queryWithClassName:@"Memory"];
        //字符串查询  
        [query whereKey:@"userName" hasPrefix:array.firstObject[@"username"]];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            
            for (AVObject *object in objects) {
                
                if ([object[@"userName"] isEqualToString:array.firstObject[@"username"]]) {
                    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:object[@"image"],@"image",object[@"title"],@"title",object[@"subtitle"],@"subtitle",object[@"content"],@"content",object[@"objectId"],@"objectId",nil];
                    [self.dataSource addObject:dic];
                }
            }
            [self.collectionView reloadData];
        }];
    }];
    AVQuery *query = [AVQuery queryWithClassName:@"Memory"];
    //字符串查询
    [query whereKey:@"userName" hasPrefix:[AVUser currentUser].username];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        
        for (AVObject *object in objects) {
            
            if ([object[@"userName"] isEqualToString:[AVUser currentUser].username]) {
                NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:object[@"image"],@"image",object[@"title"],@"title",object[@"subtitle"],@"subtitle",object[@"content"],@"content",object[@"objectId"],@"objectId",nil];
                [self.dataSource addObject:dic];
            }
        }
        [self.collectionView reloadData];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return [collectionView showMessage:@"还没有回忆噢!快去书写你们的记忆" byDataArrayCount:self.dataSource.count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    MainModel *mainModel = [[MainModel alloc] init];
    [mainModel setValuesForKeysWithDictionary:self.dataSource[indexPath.item]];
    XLPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];
    [cell setCellWithModel:mainModel];
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(LongAction:)];
    //轻扫方向
    swipe.direction = UISwipeGestureRecognizerDirectionUp;
    [cell addGestureRecognizer:swipe];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    self.hidesBottomBarWhenPushed = YES;
    MainModel *mainModel = [[MainModel alloc] init];
    [mainModel setValuesForKeysWithDictionary:self.dataSource[indexPath.row]];
    UIStoryboard *main = [UIStoryboard storyboardWithName:@"ZYMain" bundle:nil];
    DetailViewController *detailViewController = [main instantiateViewControllerWithIdentifier:@"DetailViewController"];
    detailViewController.model = mainModel;
    [self.navigationController pushViewController:detailViewController animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

#pragma mark - 删除图片（手势的回调方法）
- (void)LongAction:(UILongPressGestureRecognizer *)sender{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"删除日记" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        UICollectionViewCell *cell = (UICollectionViewCell *)sender.view;
        NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
        
        if (self.dataSource.count > 1) {
            
            [UIView animateWithDuration:0.5 animations:^{
                
                NSLog(@"%@",[self.dataSource objectAtIndex:indexPath.row][@"objectId"]);
                
                [AVQuery doCloudQueryInBackgroundWithCQL:[NSString stringWithFormat:@"delete from Memory where objectId='%@'",[self.dataSource objectAtIndex:indexPath.row][@"objectId"]] callback:^(AVCloudQueryResult *result, NSError *error) {
                    
                    [self.dataSource removeObjectAtIndex:indexPath.row];
                    [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
                }];
            }];
        } else {
            
            [UIView animateWithDuration:0.5 animations:^{
                
                [AVQuery doCloudQueryInBackgroundWithCQL:[NSString stringWithFormat:@"delete from Memory where objectId='%@'",[self.dataSource objectAtIndex:indexPath.row][@"objectId"]] callback:^(AVCloudQueryResult *result, NSError *error) {
                    
                    [self.dataSource removeAllObjects];
                    [self.collectionView reloadData];
                }];
            }];
        }
        
    }];
    [alertController addAction:sureAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - 编辑按钮
- (IBAction)publishAction:(UIBarButtonItem *)sender {
    
    self.hidesBottomBarWhenPushed = YES;
    UIStoryboard *main = [UIStoryboard storyboardWithName:@"ZYMain" bundle:nil];
    PublishViewController *publishVC = [main instantiateViewControllerWithIdentifier:@"PublishViewController"];
    publishVC.delegate = self;
    [self.navigationController pushViewController:publishVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

//协议方法
- (void)sendValue {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self.collectionView reloadData];
    });
}

#pragma mark - 懒加载
- (WZXLOLCardLayout *)layout {
    
    if (!_layout) {
        
        _layout = [[WZXLOLCardLayout alloc] init];
    }
    return _layout;
}

- (NSMutableArray *)dataSource {
    
    if (!_dataSource) {
        
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

#pragma mark - 工具方法
//UIImage转换NSData
- (NSData *)makeImageToData:(UIImage *)image {
    
    NSData *imageData = UIImageJPEGRepresentation(image, 2.0);
    return imageData;
}

//NSData转换为UIImage
- (UIImage *)makeDataToImage:(NSData *)data{
    
    UIImage *image = [UIImage imageWithData:data];
    return image;
}

//数组读取
- (NSMutableArray *)readArray {
    
    NSString *path = [[SandBoxPaths documentsPath] stringByAppendingPathComponent:@"Memory.plist"];
    NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path];
    return array;
}

//数组写入
- (void)writeToWithMemory:(NSMutableArray *)array {
    
    NSString *path = [[SandBoxPaths documentsPath] stringByAppendingPathComponent:@"Memory.plist"];
    [array writeToFile:path atomically:YES];
}

@end
